package com.xiaotao.learn.reflect;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Retention(RetentionPolicy.RUNTIME)
@interface Resource {

}

class Entity {
    @Resource
    private String name;
    @Resource
    private Date date;
    private int age;

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public Date getDate() {
        return date;
    }

    @Override
    public String toString() {
        return "Entity{" +
                "name='" + name + '\'' +
                ", date=" + date +
                ", age=" + age +
                '}';
    }
}

class FakeSpring {
    private static final Map<String, Object> container = new HashMap<>();
    public static void addBean(String name, Object bean) {
        container.put(name, bean);
    }
    public static Object getBean(String name) {
        return container.get(name);
    }

    public static <T> T getBean(String name, Class<T> c) {
        return (T)getBean(name);
    }

    /**
     * 对传入的对象的字段填充SpringIOC容器中对应的Bean
     * @param obj
     */
    public static void pad(Object obj) throws IllegalAccessException {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 若字段中存在@Resource注解，就把对应的Bean弄进去
            if (field.getAnnotation(Resource.class) != null) {
                String name = field.getName();
                field.setAccessible(true);
                Object value = container.get(name);
                field.set(obj, value);
            }
        }
    }
}

public class Main {
    public static void main(String[] args) throws IllegalAccessException {

        // <bean />@Bean @Service @Component @Controller @RestController @Configuration
        /*
          <bean name="name" class="java.lang.String">
              <constructor>
                  <param>"xiaotao"</param>
              </constructor>
          </bean>
         */
        FakeSpring.addBean("name", "xiaotao");
        FakeSpring.addBean("date", new Date());


        Date date = FakeSpring.getBean("date", Date.class);

        // 创建空对象
        // @Component
        Entity e = new Entity();
        // 当前对象状态
        System.out.println(" =========== 字段注入前 ==============");
        System.out.println(e);
        FakeSpring.pad(e);
        System.out.println(" =========== 字段注入后 ==============");
        System.out.println(e);

    }
}
